from rest_framework import serializers
from .models import UserModel,Resource,UserRole,personRole,deposit,privacy,ServiceOrder,WithModel,Service,Role,RoleResource,Workflow,WorkflowPermission
import re


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserModel
        fields = ['id', 'username', 'email', 'avatar', 'mobile', 'password']
        # 注意：不要包含密码字段，以确保安全
        extra_kwargs = {
            'username': {'required': True, 'error_messages': {"unique": "用户名已存在"}},
            'email': {'required': True, 'error_messages': {'unique': '邮箱已被注册'}},
            'password': {'write_only': True, 'required': True},
            'mobile': {'required': True},
        }
    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        email = attrs.get('email')
        mobile = attrs.get('mobile')

        # 验证用户名
        if not username:
            raise serializers.ValidationError("请输入用户名")
        if len(username) < 3:
            raise serializers.ValidationError("用户名长度必须大于等于3位")
        if len(username) > 16:
            raise serializers.ValidationError("用户名长度必须小于等于16位")

        # 验证密码
        if not password:
            raise serializers.ValidationError("请输入密码")
        if len(password) < 6:
            raise serializers.ValidationError("密码长度必须大于等于6位12")

        # 验证邮箱或手机号
        if not (email or mobile):
            raise serializers.ValidationError("请至少提供一个认证方式")
        if email and not re.match(r'^\w+@\w+.\w+$', email):
            raise serializers.ValidationError("请输入正确的邮箱")
        if mobile and not re.match(r'^1[3-9]\d{9}$', mobile):
            raise serializers.ValidationError("请输入正确的手机号")

        return super().validate(attrs)
    def create(self, validated_data):
        email = validated_data.get('email')
        mobile = validated_data.get('mobile')
        password = validated_data.get('password')
        username = validated_data.get('username')
        if email is None or mobile is None or password is None:
            raise serializers.ValidationError("请至少提供一个认证方式")
        #判断username和email和手机号是否存在
        if UserModel.objects.filter(username=username).exists():
            raise serializers.ValidationError("用户名已存在")
        if UserModel.objects.filter(email=email).exists():
            raise serializers.ValidationError("邮箱已被注册")
        if UserModel.objects.filter(mobile=mobile).exists():
            raise serializers.ValidationError("手机号已被注册")
        user = UserModel.objects.create(
            username=username,
            email=email,
            mobile=mobile,
            password=password,
            avatar = "avatar/touxiang.jpg"
        )
        user.save()
        return user



#资源表序列化器
class ResourceSerializer(serializers.ModelSerializer):
    #输出外键的描述名称
    dpname = serializers.ReadOnlyField(source='pname.name')
    dsname = serializers.ReadOnlyField(source='sname.name')

    class Meta:
        model = Resource
        fields = ['id', 'name', 'url', 'pname',"dpname",'sname','dsname']
    #处理数据一级标题即dpname和dsname都为空,二级标题即sname为空且dpname不为空,三级标题即sname不为空且dpname不为空,处理标注上都是几级标题
    def to_representation(self, instance):
        data = super().to_representation(instance)
        if instance.pname is None and instance.sname is None:
            data['level'] = 1
        elif instance.pname is not None and instance.sname is None:
            data['level'] = 2
        else:
            data['level'] = 3
        return data



#用户角色表
class UserRoleSerializer(serializers.ModelSerializer):
    # 输出外键的描述名称
    useride = serializers.ReadOnlyField(source='userid.name')
    roleide = serializers.ReadOnlyField(source='roleid.name')
    class Meta:
        model = UserRole
        fields = ['id','useride', 'roleide']


# 人员管理
class Peoplerole(serializers.ModelSerializer):
    class Meta:
        model = personRole
        fields = ["id","name","mobile","get_type_display","get_state_display"]


# 保证金管理
class DepositSerializer(serializers.ModelSerializer):
    class Meta:
        model = deposit
        fields = "__all__"


# 隐私协议
class PrivacySerializer(serializers.ModelSerializer):
    class Meta:
        model = privacy
        fields = "__all__"


# 订单表
class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = ServiceOrder
        fields = "__all__"


# 提现
class WithSer(serializers.ModelSerializer):
    class Meta:
        model = WithModel
        fields = "__all__"
# 服务表
class ServiceSer(serializers.ModelSerializer):
    class Meta:
        model = Service
        fields = "__all__"



# 角色表
class RoleSerializer(serializers.ModelSerializer):
    resources = serializers.SerializerMethodField()
    inheritedRoleName = serializers.SerializerMethodField()

    class Meta:
        model = Role
        fields ="__all__"
        # fields = ['id', 'name', 'pid', 'inheritedRoleName', 'resources']

    # def get_resources(self, obj):
    #     role_resources = RoleResource.objects.filter(roleid=obj)
    #     resource_ids = [r.resourceid.id for r in role_resources]
    #     resources = Resource.objects.filter(id__in=resource_ids)
    #     if resources.count() != len(resource_ids):
    #         raise ValueError("All resource IDs must exist in the Resource table.")
    #     return ResourceSerializer(resources, many=True).data
    # def get_inheritedRoleName(self, obj):
    #     return obj.pid.name if obj.pid else '无'
    # def create(self, validated_data):
    #     role = Role.objects.create(**validated_data)
    #     # 获取资源数据
    #     resources_data = self.initial_data.get('resources', [])
    #     # 为每个资源创建 RoleResource 记录
    #     for resource_data in resources_data:
    #         RoleResource.objects.create(roleid_id=role.id, resourceid_id=resource_data['resourceid_id'])
    #     return role
# class RoleResourceSerializer(serializers.ModelSerializer):
#     resource_name = serializers.CharField(source='resourceid.name', read_only=True)
#
#     class Meta:
#         model = RoleResource
#         fields = ["id", "resourceid_id", "roleid_id", "resource_name"]




# 角色资源表
class UserResourceSerializer(serializers.ModelSerializer):
    class Meta:
        model = RoleResource
        fields = "__all__"



# 角色资源表序列化器
class RoleResourceSerializer(serializers.ModelSerializer):
    class Meta:
        model = RoleResource
        fields = "__all__"

class WorkflowSerializer(serializers.ModelSerializer):
    class Meta:
        model = Workflow
        fields = "__all__"

class WorkflowPermissionSerializer(serializers.ModelSerializer):
    role_name = serializers.CharField(source='roleid.name', read_only=True)
    workflow_name = serializers.CharField(source='workflowid.name', read_only=True)
    class Meta:
        model = WorkflowPermission
        fields = ['id','roleid_id','workflowid_id','role_name','workflow_name']